<template>
  <view class="page page-primary page-transparent">
    <page-header theme="transparent" :showPlaceHolder="false" :showTitle="false"></page-header>
    <view class="page-content">
      <view class="header-con">
        <view class="title">
          {{ currentStepText }}
        </view>
        <view class="title">
          {{ currentStepText }}金额 ¥{{utils.moneyFormatter(orderData.totalPrice / 100)}}
        </view>
      </view>
      <view class="content">
        <view class="invoice-con">
          <fui-steps :items="invoiceStepList" :isMark='false' activeColor="#333333" size="24" :current="currentStep"></fui-steps>
          <view class="info">
            <view class="info-con">
              <text class="label">发票类型</text>
              <text>电子普通发票</text>
            </view>
            <view class="info-con">
              <text class="label">抬头类型</text>
              <text>{{showInvoiceData.titleType == '0' ? '个人' : '公司'}}</text>
            </view>
            <view class="info-con">
              <text class="label">抬头名称</text>
              <text>{{showInvoiceData.title}}</text>
            </view>
            <view class="info-con">
              <text class="label">开票金额</text>
              <text>¥{{utils.moneyFormatter(orderData.totalPrice / 100)}}</text>
            </view>
            <view class="info-con">
              <text class="label">申请时间</text>
              <text>{{formatDateTime(orderData.createTime)}}</text>
            </view>
            <view class="info-con" v-if="currentStep === 2">
              <text class="label">开票时间</text>
              <text>{{ formatDateTime(invoiceData.createTime) }}</text>
            </view>
            <view class="info-con" v-if="currentStep === 2">
              <text class="label">发票附件</text>
              <view class="file-wrapper">
                <upload-image childId="previewInvoince" :isPreview="true" type="all" :defaultList="defaultList"></upload-image>
              </view>
              <!-- <view class="img">
                <image :src="invoiceData.file" mode=""></image>
              </view> -->
            </view>
          </view>
        </view>
        <view class="order-list">
          <view class="order-item">
            <view class="order-title">订单编号<span>{{orderData.no}}</span></view>
            <view class="order-list-content" v-for="item in orderData.items" :key="item.id">
              <image :src="item.picUrl" style="width: 132rpx; height: 132rpx; border-radius: 16rpx; overflow: hidden;" mode=""></image>
              <view class="content-right">
                <view class="content-right-title">
                  <view class="content-right-title-left">{{item.spuName}}</view>
                  <view class="content-right-title-right"><span>￥</span>{{utils.moneyFormatter(item.price / 100)}}</view>
                </view>
                <view class="content-right-num">x{{item.count}}
                </view>
              </view>
            </view>
            
            
            <view class="order-list-bottom">
              <span>实付款：</span>¥{{utils.moneyFormatter(orderData.totalPrice / 100)}}
            </view>
          </view>
        </view>
      </view>

      <view class="ui-fixed-footer" v-if="currentStep === 1">
        <fui-button height="78rpx" background="var(--fui-color-primary)" bold @click="submit">确认开票</fui-button>
      </view>

      <fui-modal :buttons="[]" width="662" :show="showInvoiceDialog" maskClosable @cancel="onCancel">
        <view class="fui-icon__close" @tap="onCancel">
          <view class="title">
            发票附件
          </view>
          <fui-icon name="close" color="#B2B2B2" :size="48"></fui-icon>
        </view>
        <view class="upload" style="padding: 20rpx;width: 420rpx;">
          <upload-image type="all" formats="pdf,png,jpg,jpeg" :defaultList="defaultList" @uploaded="uploadedInvoice"></upload-image>
        </view>
        <view class="tips" v-if="!invoiceForm.file">
          请上传发票附件
        </view>
        <view class="btns">
          <fui-button width="230rpx" bold height="72rpx" radius="48rpx" background="#FFFFFF" color="var(--fui-color-primary)" borderColor="var(--fui-color-primary)" borderWidth="2px" @click="onCancel">取消</fui-button>
          <fui-button bold width="230rpx" height="72rpx" color="#FFFFFF" background="var(--fui-color-primary)" radius="48rpx" disabledBackground="#DFDFDF" disabledColor="#666666" @click="confirm">确认</fui-button>
        </view>
      </fui-modal>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import pageHeader from '@/components/header'
import { useStore } from 'vuex'
import orderApi from '@/api/order'
import utils from '@/components/firstui/fui-utils'
import uploadImage from '@/components/upload/image'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

// 开票表单信息
const invoiceForm = ref({})

// 开票流程
const invoiceStepList = [{
  title: '订单提交',
  src: '/static/images/step_active.png',
  activeSrc: '/static/images/step.png'
}, {
  title: '订单完成',
  src: '/static/images/step_active.png',
  activeSrc: '/static/images/step.png'
}, {
  title: '开票完成',
  src: '/static/images/step_active.png',
  activeSrc: '/static/images/step.png'
}]

// 时间格式化
const formatDateTime = (date) => {
  return utils.dateFormatter(date, 'y-m-d h:i:s', 2)
}

// 获取订单详情
const params = ref({})
const orderData = ref({})
const getOrderDetail = () => {
  try {
    orderApi.getOrderDetail(params.value.orderId).then((res) => {
      if (res.code === 0) {
        orderData.value = {
          ...res.data,
          title: res.data.items[0].spuName,
          imgUrl: res.data.items[0].picUrl,
          price: res.data.items[0].price,
          totalPrice: res.data.totalPrice,
          deliveryPrice: res.data.deliveryPrice,
          payPrice: res.data.payPrice
        }

        invoiceForm.value.payOrderId = orderData.value.payOrderId
        invoiceForm.value.orderId = orderData.value.id
        invoiceForm.value.userId = orderData.value.userId
        invoiceForm.value.amount = res.data.totalPrice
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch (e) {
    modal.msgError('获取订单详情数据失败')
  }
}

const currentStep = computed(() => invoiceData.value.file ? 2 : 1)
const currentStepText = computed(() => invoiceData.value.file ? '已开票' : '待开票')

// 获取待开票抬头信息
const invoiceTitleData = ref({})
const getOrderInvoiceTitle = () => {
  try {
    orderApi.getOrderInvoiceTitle(params.value.invoiceTitleId).then((res) => {
      if (res.code === 0) {
        invoiceTitleData.value = res.data || {}

        invoiceForm.value.titleType = invoiceTitleData.value.titleType
        invoiceForm.value.title = invoiceTitleData.value.name
        invoiceForm.value.receiveEmail = invoiceTitleData.value.receiveEmail
        invoiceForm.value.taxationNum = invoiceTitleData.value.taxationNum
        invoiceForm.value.address = invoiceTitleData.value.address
        invoiceForm.value.telephone = invoiceTitleData.value.telephone
        invoiceForm.value.bankName = invoiceTitleData.value.bankName
        invoiceForm.value.bankAccount = invoiceTitleData.value.bankAccount
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch (e) {
    modal.msgError('获取开票信息失败')
  }
}

// 获取已开票数据
const invoiceData = ref({})
const defaultList = computed(() => invoiceForm.value.file ? [invoiceForm.value.file] : [])
const getOrderInvoiceDetail = () => {
  try {
    orderApi.getOrderInvoiceDetail(params.value.orderId).then((res) => {
      if (res.code === 0) {
        invoiceData.value = res.data || {}

        invoiceForm.value.file = invoiceData.value.file ? invoiceData.value.file : ''
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch (e) {
    modal.msgError('获取开票信息失败')
  }
}

const showInvoiceData = computed(() => {
  return invoiceData.value.file ? invoiceData.value : invoiceForm.value
})

onLoad((option) => {
  params.value = { ...option }
  getOrderDetail()
  getOrderInvoiceTitle()
  getOrderInvoiceDetail()
})

// 开具发票操作
const showInvoiceDialog = ref(false)
const uploadedInvoice = ((e) => {
  if (e[0]) {
    invoiceForm.value.file = e[0]
  } else {
    invoiceForm.value.file = ''
  }
})
const submit = (() => {
  invoiceForm.value.file = ''
  showInvoiceDialog.value = true
})
const onCancel = (() => {
  showInvoiceDialog.value = false
})
const confirm = (() => {
  if (!invoiceForm.value.file) {
    modal.msgError('请先上传发票附件！')
    return
  }
  showInvoiceDialog.value = false
  try {
    orderApi.addOrderInvoice(invoiceForm.value).then((res) => {
      if (res.code === 0) {
        modal.msgError('发票开具完成！')
        getOrderInvoiceDetail()
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch (e) {
    modal.msgError('发票开具失败！')
  }
})
</script>

<style lang="scss">
page {
  background-color: #f2f4f5;
}

::v-deep.fui-steps__wrap {
  padding-right: 10rpx !important;
}

::v-deep.fui-upload__wrap {
  padding: 38rpx 42rpx !important;
  height: 268rpx !important;
}

.fui-icon__close {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
}

::v-deep.fui-modal__inner {
  padding: 26rpx 32rpx !important;
}

.page {
  min-height: 100%;
  position: relative;

  .page-content {
    padding: 0;
  }

  .header-con {
    height: 354rpx;
    background: var(--fui-color-primary);
    opacity: 1;
    position: relative;
    top: -1px;
    padding: 0 28rpx;

    .title {
      font-size: 40rpx;
      font-weight: bold;
      color: #ffffff;
      text-align: center;
    }

    .title:first-child {
      padding-top: 80rpx;
      padding-bottom: 8rpx;
    }
  }

  .content {
    margin-top: 50rpx;
    padding: 0 42rpx;
    position: absolute;
    left: 0;
    right: 0;
    top: 246rpx;
    background: #f2f4f5;

    .invoice-con {
      padding: 54rpx 42rpx 48rpx 42rpx;
      background: #ffffff;
      border-radius: 16rpx 16rpx 16rpx 16rpx;
      opacity: 1;

      .info {
        margin-top: 74rpx;

        .info-con:last-child {
          margin-bottom: 0;
          display: flex;
        }

        .info-con {
          font-size: 28rpx;
          font-weight: bold;
          color: #333333;
          margin-bottom: 36rpx;

          .label {
            flex: 0 0 120rpx;
            padding-right: 88rpx;
          }

          .file-wrapper {
            width: calc(100% - 208rpx);
          }

          .img {
            width: 184rpx;
            height: 116rpx;
            border: 10rpx solid #eeeeee;

            image {
              width: 100%;
              height: 100%;
              display: block;
            }
          }
        }
      }
    }
  }

  .order-list {
    margin-top: 30rpx;
    .order-item {
      width: 100%;
      background: #ffffff;
      border-radius: 16rpx;
      margin-bottom: 180rpx;
      overflow: hidden;

      .order-title {
        width: 100%;
        height: 78rpx;
        line-height: 78rpx;
        padding: 0 28rpx;
        font-size: 28rpx;
        font-weight: bold;
        color: #333333;
        background: linear-gradient(
          93deg,
          #e9efff 0%,
          rgba(255, 255, 255, 0.05) 80%
        );
        box-sizing: border-box;

        span {
          padding-left: 20rpx;
        }
      }

      .order-list-content {
        width: calc(100% - 56rpx);
        padding: 24rpx 0;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        border-top: 1px solid #f1f1f1;
        margin: 0 28rpx;
        &:first-child{
          border-top: 0px solid #f1f1f1;
        }

        .content-right {
          width: calc(100% - 172rpx);
          font-size: 28rpx;
          font-weight: bold;
          color: #333333;
          line-height: 40rpx;

          .content-right-title {
            display: flex;
            justify-content: space-between;
            
            .content-right-title-left{
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .content-right-title-right {
              font-size: 36rpx;

              span {
                font-size: 24rpx;
              }
            }
          }

          .content-right-num {
            font-size: 24rpx;
            font-weight: 400;
            color: #666666;
          }
        }

        .right-list {
          display: flex;
          flex-wrap: wrap;

          .right-text {
            width: 50%;
            font-size: 24rpx;
            font-weight: 400;
            color: #999999;
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;

            image {
              padding-right: 10rpx;
            }

            span {
              color: #333333;
            }

            .right-number {
              font-weight: bold;
              color: var(--fui-color-link);
              padding: 0 10rpx;
            }
          }
        }
      }

      .order-list-bottom {
        width: calc(100% - 56rpx);
        padding: 12rpx 0rpx 20rpx;
        margin: 18rpx auto 0;
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
        border-top: 1px solid #f1f1f1;
        text-align: right;

        span {
          font-size: 28rpx;
          color: #666666;
        }
      }
    }
  }

  .ui-fixed-footer {
    background-color: #f2f4f5 !important;
  }

  .upload {
    margin-top: 88rpx;
  }

  .tips {
    font-size: 24rpx;
    font-weight: 400;
    color: #fea137;
    margin-top: 28rpx;
  }

  .btns {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    width: 100%;
    margin-top: 104rpx;
  }
}
</style>